package com.ruoyi.system.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.annotation.ExcelProperty;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.system.domain.InvoiceGroup;
import com.ruoyi.system.domain.MonthlySettlement;
import com.ruoyi.system.service.IInvoiceGroupService;
import com.ruoyi.system.service.IInvoiceRecordsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/system/records/upload")
public class MonthlySettlementController extends BaseController {
    @Autowired
    private IInvoiceRecordsService invoiceRecordsService;
    @Autowired
    private IInvoiceGroupService invoiceGroupService;
    /**
     * 月结报表
     */
    @Anonymous
    @RequestMapping("/export")
    public void export(HttpServletResponse response,@RequestParam(value = "startTime",required = true)String startTime,
                       @RequestParam(value = "provide",required = false)String provide1) throws Exception{
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        StringBuffer fileNameBuffer = new StringBuffer("");
        fileNameBuffer.append("monthlySettlement").append("-").append(sdf.format(new Date())).append(".xls");
        String filename = URLEncoder.encode(fileNameBuffer.toString(), "UTF-8");
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=" + filename );

        List<MonthlySettlement> cutterControlList = listMoneyInfo(startTime,provide1);
        EasyExcel.write(response.getOutputStream(), MonthlySettlement.class)
                .sheet("月结数据")
                .doWrite(cutterControlList);
    }

    /**
     * 导出数据
     * @return
     */
   /* @Anonymous
    @RequestMapping("/export")
    public String export(HttpServletResponse response,@RequestParam(value = "startTime",required = true)String startTime,
                         @RequestParam(value = "provide",required = false)String provide1){

        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
            StringBuffer fileNameBuffer = new StringBuffer("");
            fileNameBuffer.append(startTime+"月结和明细多表导出").append("-").append(sdf.format(new Date())).append(".xls");
            String filename = URLEncoder.encode(fileNameBuffer.toString(), "UTF-8");
            //定义导出信息
            //表名定义
            String shellNameObjects[] = {
                    "月结表" , "明细表"
            };
            //列名定义
            String shellHeaderObjects[][] = new String[][]{
                    {"厂家", "压库金额", "买断金额" , "合计金额"},
                    {"产品编码","产品名称","型号","规格","售价","进价","数量","金额","品牌","供应商","结算模式"}
            };
            //创建工作表
            HSSFWorkbook wb = new HSSFWorkbook();
            HSSFCellStyle style = wb.createCellStyle();
            //style.setAlignment(HSSFCellStyle.align);
           // .ALIGN_JUSTIFY
            *//***************  创建表1 （月结表） ****************//*
            //创建表格名称
            HSSFSheet sheet0 = wb.createSheet(shellNameObjects[0]);
            //设置每行每列单元格大小
            sheet0.autoSizeColumn(1, true);
            //单独设置每列的宽度：这个非常有用，假设有些列内容过长时，就需要设置一定的长度显示内容了。不设置则使用默认宽度。
            sheet0.setColumnWidth(0 , 25 * 256);
            //sheet0.setColumnWidth(2 , 80 * 256);
            //创建（填充）表格标题（表格第一行）
            HSSFRow sheet0HeaderRow = sheet0.createRow(0);
            sheet0HeaderRow.setHeightInPoints(20);//目的是想把行高设置成20px
            for (int i = 0; i < shellHeaderObjects[0].length; i++) {
                HSSFCell cell = sheet0HeaderRow.createCell((short) i);
                cell.setCellValue(shellHeaderObjects[0][i]);
                cell.setCellStyle(style);
            }
            List<MonthlySettlement>  list=listMoneyInfo(startTime,provide1);
            //填充表格（单元格）内容
            if (null != list && list.size() > 0)
            {
                //从表格第二行开始填充，因为第一行已经填充标题了
                int index = 1;
                for (MonthlySettlement bean: list){
                    HSSFRow sheetRow = sheet0.createRow(index);
                    sheetRow.setHeightInPoints(30);//目的是想把行高设置成20px
                    sheetRow.createCell(0).setCellValue(bean.getProvide());
                    if(bean.getYqMoney()!=null){
                        sheetRow.createCell(1).setCellValue(bean.getYqMoney());
                    }
                    if(bean.getMdMoney()!=null){
                        sheetRow.createCell(2).setCellValue(bean.getMdMoney());
                    }
                    if(bean.getTotalMoney()!=null){
                        sheetRow.createCell(3).setCellValue(bean.getTotalMoney());
                    }
                    index++;
                }
            }

            *//***************  创建表2 （明细表） ****************//*
            //创建表格名称
            HSSFSheet sheet1 = wb.createSheet(shellNameObjects[1]);
            //设置每行每列单元格大小
            sheet1.autoSizeColumn(1, true);
            //单独设置每列的宽度：这个非常有用，假设有些列内容过长时，就需要设置一定的长度显示内容了。不设置则使用默认宽度。
            sheet1.setColumnWidth(0 , 25 * 256);
            //sheet1.setColumnWidth(2 , 80 * 256);
            //创建（填充）表格标题（表格第一行）
            HSSFRow sheet1HeaderRow = sheet1.createRow(0);
            sheet1HeaderRow.setHeightInPoints(20);//目的是想把行高设置成20px
            for (int i = 0; i < shellHeaderObjects[1].length; i++) {
                HSSFCell cell = sheet1HeaderRow.createCell((short) i);
                cell.setCellValue(shellHeaderObjects[1][i]);
                cell.setCellStyle(style);
            }
            InvoiceRecords invoiceRecords =new InvoiceRecords();
            invoiceRecords.setProvide(provide1);
            List<Map<String,Object>> list1=listWebInfo("",provide1,"","","",startTime);
            //填充表格（单元格）内容
            if (null != list1 && list1.size() > 0)
            {
                //从表格第二行开始填充，因为第一行已经填充标题了
                int index = 1;
                for (Map<String,Object> bean: list1){
                    HSSFRow sheetRow = sheet1.createRow(index);
                    sheetRow.setHeightInPoints(30);//目的是想把行高设置成20px
                    sheetRow.createCell(0).setCellValue(""+bean.get("product_name"));
                    sheetRow.createCell(1).setCellValue(""+bean.get("product_code"));
                    sheetRow.createCell(2).setCellValue(""+bean.get("model"));
                    sheetRow.createCell(3).setCellValue(""+bean.get("specs"));
                    sheetRow.createCell(4).setCellValue(""+bean.get("product_price"));
                    sheetRow.createCell(5).setCellValue(""+bean.get("plarn_price"));
                    sheetRow.createCell(6).setCellValue(""+bean.get("count"));
                    sheetRow.createCell(7).setCellValue(""+bean.get("plarn_money"));
                    sheetRow.createCell(8).setCellValue(""+bean.get("product_brand"));
                    sheetRow.createCell(9).setCellValue(""+bean.get("provide"));
                    sheetRow.createCell(10).setCellValue(""+bean.get("settlement_mode"));
                    index++;
                }
            }



            // 回去输出流
            OutputStream out = response.getOutputStream();
            response.setHeader("Cache-Control", "private");
            response.setHeader("Pragma", "private");
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Type", "application/force-download");
            response.setHeader("Content-disposition", "attachment;filename=" + filename);
            wb.write(out);
            out.flush();
            out.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }*/
    public List<Map<String,Object>> listWebInfo(String productName,String provide,String company,String status,String productGroup,String startTime)
    {
        List<Map<String,Object>> list = invoiceRecordsService.listWebInfo(productName,provide,company,status,productGroup,startTime);
        Double allMoney = invoiceRecordsService.selectAllMoney(provide, startTime);
        for (Map<String,Object> map:list) {
            String productCode = map.get("product_code").toString();
            InvoiceGroup invoiceGroup = new InvoiceGroup();
            invoiceGroup.setProductCode(productCode);
            List<InvoiceGroup> invoiceGroups = invoiceGroupService.selectInvoiceGroupList(invoiceGroup);
            if(invoiceGroups!=null){
                map.put("groupList",invoiceGroups);
            }
            map.put("allMoney",allMoney);
        }
        return list;
    }
    public List<MonthlySettlement> listMoneyInfo(String startTime,String provide1){
        List<MonthlySettlement> hashMapList = new ArrayList<>();
        List<String> list = invoiceRecordsService.listProvide(provide1);
        for (String provide:list) {
            MonthlySettlement hashMap = new MonthlySettlement();
            //厂家
            hashMap.setProvide(provide);
            List<Map<String, Object>> maps = invoiceRecordsService.listSumMoney(provide,startTime);
            hashMap.setYqMoney(0.0);
            hashMap.setMdMoney(0.0);
            hashMap.setYypj(0.0);
            hashMap.setYyrhy(0.0);
            hashMap.setYyzlj(0.0);
            hashMap.setYylt(0.0);
            hashMap.setCmpj(0.0);
            hashMap.setCmrhy(0.0);
            hashMap.setCmzlj(0.0);
            hashMap.setCmlt(0.0);
            hashMap.setJspj(0.0);
            hashMap.setJsrhy(0.0);
            hashMap.setJszlj(0.0);
            hashMap.setJslt(0.0);
            hashMap.setIsFz("未封账");
            Double otherMoney = 0.0;
            List<Map<String, Object>> maps2 = invoiceRecordsService.listOtherMoney(provide,startTime);
            if(maps2!=null&&maps2.size()>0){
                for (Map<String,Object> map:maps2) {
                    otherMoney = Double.valueOf(map.get("sumMoney").toString());
                }
            }
            hashMap.setOtherMoney(new BigDecimal(String.valueOf(otherMoney)).setScale(2, RoundingMode.HALF_UP).doubleValue());
            int count = 0;
            for (Map<String,Object> map:maps) {
                if(map.get("settlement_mode")!=null && map.get("settlement_mode").equals("压库")){
                    //压库金额
                    if(map.get("status").equals("1")){
                        count++;
                    }
                    hashMap.setYqMoney(new BigDecimal(""+map.get("sumMoney")).setScale(2, RoundingMode.HALF_UP).doubleValue());
                }else if(map.get("settlement_mode")!=null && map.get("settlement_mode").equals("买断")){
                    //买断金额
                    if(map.get("status").equals("1")){
                        count++;
                    }
                    hashMap.setMdMoney(new BigDecimal(""+map.get("sumMoney")).setScale(2, RoundingMode.HALF_UP).doubleValue());
                }
                //合金金额
                hashMap.setTotalMoney(new BigDecimal(String.valueOf(hashMap.getYqMoney()+hashMap.getMdMoney())).setScale(2, RoundingMode.HALF_UP).doubleValue());
            }
            if(count == maps.size()){
                hashMap.setIsFz("封账");
            }
            List<Map<String, Object>> maps1 = invoiceRecordsService.listGroupMoney(provide,startTime);
            for (Map<String,Object> map:maps1) {
                if(map.get("company")!=null && map.get("company").equals("营运公司")){
                    if(map.get("product_group")!=null &&  map.get("product_group").equals("配件")){
                        hashMap.setYypj(new BigDecimal(""+map.get("groupMoney")).setScale(2, RoundingMode.HALF_UP).doubleValue());
                    }else if(map.get("product_group")!=null && map.get("product_group").equals("润滑油")){
                        hashMap.setYyrhy(new BigDecimal(""+map.get("groupMoney")).setScale(2, RoundingMode.HALF_UP).doubleValue());
                    }else if(map.get("product_group")!=null && map.get("product_group").equals("制冷剂")){
                        hashMap.setYyzlj(new BigDecimal(""+map.get("groupMoney")).setScale(2, RoundingMode.HALF_UP).doubleValue());
                    }else if(map.get("product_group")!=null && map.get("product_group").equals("轮胎")){
                        hashMap.setYylt(new BigDecimal(""+map.get("groupMoney")).setScale(2, RoundingMode.HALF_UP).doubleValue());
                    }
                }else if(map.get("company")!=null && map.get("company").equals("崇明巴士")){
                    if(map.get("product_group")!=null && map.get("product_group").equals("配件")){
                        hashMap.setCmpj(new BigDecimal(""+map.get("groupMoney")).setScale(2, RoundingMode.HALF_UP).doubleValue());
                    }else if(map.get("product_group")!=null && map.get("product_group").equals("润滑油")){
                        hashMap.setCmrhy(new BigDecimal(""+map.get("groupMoney")).setScale(2, RoundingMode.HALF_UP).doubleValue());
                    }else if(map.get("product_group")!=null && map.get("product_group").equals("制冷剂")){
                        hashMap.setCmzlj(new BigDecimal(""+map.get("groupMoney")).setScale(2, RoundingMode.HALF_UP).doubleValue());
                    }else if(map.get("product_group")!=null && map.get("product_group").equals("轮胎")){
                        hashMap.setCmlt(new BigDecimal(""+map.get("groupMoney")).setScale(2, RoundingMode.HALF_UP).doubleValue());
                    }
                }else if(map.get("company")!=null && map.get("company").equals("金山巴士")){
                    if(map.get("product_group")!=null && map.get("product_group").equals("配件")){
                        hashMap.setJspj(new BigDecimal(""+map.get("groupMoney")).setScale(2, RoundingMode.HALF_UP).doubleValue());
                    }else if(map.get("product_group")!=null && map.get("product_group").equals("润滑油")){
                        hashMap.setJsrhy(new BigDecimal(""+map.get("groupMoney")).setScale(2, RoundingMode.HALF_UP).doubleValue());
                    }else if(map.get("product_group")!=null && map.get("product_group").equals("制冷剂")){
                        hashMap.setJszlj(new BigDecimal(""+map.get("groupMoney")).setScale(2, RoundingMode.HALF_UP).doubleValue());
                    }else if(map.get("product_group")!=null && map.get("product_group").equals("轮胎")){
                        hashMap.setJslt(new BigDecimal(""+map.get("groupMoney")).setScale(2, RoundingMode.HALF_UP).doubleValue());
                    }
                }
            }
            hashMapList.add(hashMap);
        }
        return hashMapList;
    }

}
